//
//  APPLEComposeView.swift
//  123
//
//  Created by pangjiaxing on 16/1/6.
//  Copyright © 2016年 pangjiaxing. All rights reserved.
//

import UIKit
import pop
class APPLEComposeView: UIView {
    
    private lazy var childMenuButton:[APPLEComposeMenuButton]=[APPLEComposeMenuButton]()
    private lazy var sloganImageView:UIImageView = {
        let imageView=UIImageView()
        imageView.image=UIImage(named: "compose_slogan")
        return  imageView
    }()
    private lazy var target:UIViewController = UIViewController()
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setUpUI(){
        frame.size=CGSize(width: mainScreenW, height: mainScreenH)
        let imageview = UIImageView(image: UIImage.getScreenShot().applyLightEffect())
    
        addSubview(imageview)
        addSubview(sloganImageView)
        imageview.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self)
        }
        sloganImageView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.top.equalTo(self).offset(100)
        }
        
        addChildButton()
    }
    // 添加子按钮
    private func addChildButton(){
        
        let childButtonW: CGFloat = 80
        let childButtonH: CGFloat = 110
        // 每一个按钮之间的间距
        let childButtonMargin: CGFloat = (mainScreenW - 3 * childButtonW) / 4
        
        
        // 读取 plist文件路径
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!
        
        // 把 plist 文件转成 NSArray
        let composeButtonMenuInfos = NSArray(contentsOfFile: path)!
        
        for (i,value) in composeButtonMenuInfos.enumerate(){
            let button = APPLEComposeMenuButton()
            
            let dict = value as! NSDictionary
            
            // 读取图片名字
            let iconName = dict["icon"]! as! String
            // 标题
            let title = dict["title"]! as! String
            
            button.setImage(UIImage(named: iconName), forState: UIControlState.Normal)
            button.setTitle(title, forState: UIControlState.Normal)
            
            // 取到当前遍历的按钮的第 xx 行和 第 xx 列
            let col = i % 3
            let row = i / 3
            // 计算位置
            let childButtonX = CGFloat(col + 1) * childButtonMargin + CGFloat(col) * childButtonW
            let childButotnY = (childButtonH + childButtonMargin) * CGFloat(row)+mainScreenH
            // 设置 frame
            button.frame = CGRect(x: childButtonX, y: childButotnY, width: childButtonW, height: childButtonH)
            
            // 添加点击事件
            button.addTarget(self, action: "childButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            addSubview(button)
            childMenuButton.append(button)
        }
    }
    @objc private func childButtonClick(buttton:UIButton){
   
      UIView.animateWithDuration(0.25, animations: { () -> Void in
        
            for value in self.childMenuButton {
                value.alpha=0.01
                if value == buttton {
                    value.transform = CGAffineTransformMakeScale(2, 2)
                }else{
                    value.transform = CGAffineTransformMakeScale(0.2, 0.2)
                }
            }
        
        }) { (_) -> Void in
             print("点击了按钮，准备跳转到控制器AppleComposeViewController，我在AppleComposeView")
            
            //这里可以通过一个plist文件跳转不同的控制器，在转化的时候注意前面要加上weibo12. 
            //因为，swift的文件都是静态的文件。
            
            self.target.presentViewController(APPLENavigationViewController(rootViewController:APPLEComposeViewController()), animated: true, completion: { () -> Void in
                self.removeFromSuperview()
            })
            
        }
        
    }
    // 调用这个方法就展示当前View
    func show(target: UIViewController) {
        self.target = target
//        // 保存 target ，原因是为了弹出控制器
        self.target.view.addSubview(self)
//        let window:UIWindow=UIApplication.sharedApplication().keyWindow!
//        window.addSubview(self)
    }
    
    override func didMoveToWindow() {
        
        for (index,value) in childMenuButton.enumerate() {
            doAnimation(value, Index: index, isUp: true)
        }
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
        for (index,value) in childMenuButton.reverse().enumerate() {
            doAnimation(value, Index: index, isUp: false)
        }
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.4 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) {
            
            self.removeFromSuperview()
            
        }
    }
    
    private func doAnimation(button:UIButton,Index:Int,isUp:Bool=false){
        
        let animation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        var y = button.center.y + 350
        if isUp{
            y = button.center.y - 350
         }
        animation.toValue = NSValue(CGPoint: CGPoint(x: button.center.x, y: y))
        // 弹性度：[0,20]，越大，幅度越大
        animation.springBounciness = 10
        // 弹性速度：[0,20] 越小，执行的时候时间越长
        animation.springSpeed = 8
        // CACurrentMediaTime() --> 当前系统的绝对时间
        animation.beginTime = CACurrentMediaTime() + Double(Index) * 0.025
        button.pop_addAnimation(animation, forKey: nil)
    }
    
  
    
    
}
